﻿using MediatR;
using Medical.Api.Write.Application.Command.DepartmentManagement.Use;
using Medical.Domain.DepartmentInfo;
using Medical.ErrorCode;
using Medical.Interstructrue.Base;
using Microsoft.Extensions.Logging;
using System;
using System.Threading;
using System.Threading.Tasks;

namespace Medical.Api.Write.Application.Handler.DepartmentManagement.Use
{
    public class UpdateUseStatueCommandHandler : IRequestHandler<UpdateUseStatueCommands, ApiResult<int>>
    {
        private readonly IBaseRepository<UseTable> useRep;
        private readonly ILogger<UpdateUseStatueCommandHandler> logger;

        public UpdateUseStatueCommandHandler(IBaseRepository<UseTable> useRep, ILogger<UpdateUseStatueCommandHandler> logger)
        {
            this.useRep = useRep;
            this.logger = logger;
        }

        public async Task<ApiResult<int>> Handle(UpdateUseStatueCommands request, CancellationToken cancellationToken)
        {
            try
            {
                logger.LogInformation("开始处理使用表状态更新，ID：{0}，新状态：{1}", request.UseId, request.RegistrationStatue);
                
                // 检查要修改的使用记录是否存在
                var existingUse = await useRep.GetModelAsync(request.UseId);
                if (existingUse == null)
                {
                    logger.LogWarning("未找到ID为{0}的使用记录", request.UseId);
                    return new ApiResult<int>
                    {
                        Code = ApiEnums.NotFound,
                        Data = 0,
                        Msg = $"未找到ID为{request.UseId}的使用记录"
                    };
                }
                
                // 更新使用状态
                existingUse.RegistrationStatue = request.RegistrationStatue;
                existingUse.UpdateTime = DateTime.Now;
                
                // 更新使用记录 - Update方法内部已经调用了SaveChanges
                useRep.Update(existingUse);
                
                logger.LogInformation("成功更新使用表状态，ID：{0}，新状态：{1}", request.UseId, request.RegistrationStatue);
                return new ApiResult<int>
                {
                    Code = ApiEnums.Success,
                    Data = request.UseId,
                    Msg = "成功更新使用表状态"
                };
            }
            catch (Exception ex)
            {
                logger.LogError(ex, "更新使用表状态时发生错误：{0}", ex.Message);
                return new ApiResult<int>
                {
                    Code = ApiEnums.Fail,
                    Data = 0,
                    Msg = $"更新使用表状态失败：{ex.Message}"
                };
            }
        }
    }
}
